import { uploadFile } from '@UTILS/AliYunOSS'
import { OSS_TYPE } from '@CONSTANTS/app'
import { CustomI18NITF, ImageFile } from '@INTERFACES/Common'
import { getFileInfo } from '@UTILS/common'
import api from '@API'
import { date } from '@pier88health/p8h-common'
import { FieldStyle } from '@INTERFACES/MedRecord';
import { RoundType } from '@CONSTANTS/medRecord';

interface UploadPatientFileParams {
  patientId?: string;
  userId: string;
  imgs: ImageFile[];
  isUpload?: boolean
  uploadNew?: boolean
}

export const uploadPatientFile = async ({
  patientId,
  userId,
  imgs,
  isUpload = true,
  uploadNew = false
}: UploadPatientFileParams) => {
  if (!Array.isArray(imgs) || imgs.length < 1) return []
  const MedRecords = []
  for (const item of imgs) {
    const {
      fileName, ext, size, shortFileName
    } = getFileInfo(item)

    await uploadFile({
      path: item.path,
      isPrivate: true,
      type: OSS_TYPE.CaseHistory,
      folderId: `${userId}/medRecords`,
      staticName: shortFileName,
      staticExt: ext,
    })
    MedRecords.push({
      FileName: fileName,
      Title: fileName,
      Type: ext,
      Size: size
    })
  }
  if (!isUpload) return MedRecords
  await api.uploadMyPatientMedRecords({ PatientId: patientId, MedRecords, UploadNew: uploadNew })
  return MedRecords
}

function medRecordGroupBy(array: any[]) {
  const groups: Record<string, any> = {};
  array.forEach(item => {
    const group = item.FieldGroup;
    const preValue = groups[group]
    if (preValue) {
      const preChildren = preValue.Children || []
      let newStyle = preValue.FieldStyle
      if (preValue.FieldStyle === FieldStyle.Boolean) {
        newStyle = 'ShrinkBoolean'
      } else if (preValue.FieldStyle === FieldStyle.SingleChoice && preValue.Options) {
        newStyle = Object.keys(preValue.Options).length === 2 ? 'ShrinkTwo' : 'ShrinkThree'
      }
      preValue.FieldStyle = newStyle
      preValue.Children = [...preChildren, item];
    } else {
      groups[group] = item;
    }
  });
  return Object.keys(groups).map(group => groups[group]);
}

export const handlerMedRecord = (data: any[], round: string) => {
  if (!Array.isArray(data) || data.length <= 0) return {}
  const isMedFollowUp = round !== RoundType.RegisterWithDoctor
  const res: Record<string, any[]> = { PersonalInfo: [], VisitorInfo: [], ConditionInfo: [] }
  const personalHeaderIndex = data.findIndex(item => item.FieldGroup === (isMedFollowUp ? 'PersonalHeader2' : 'PersonalHeader'))
  const visitorHeaderIndex = data.findIndex(item => item.FieldGroup === 'VisitorHeader')
  const conditionHeaderIndex = data.findIndex(item => item.FieldGroup === 'ConditionHeader')
  if (isMedFollowUp) {
    res.PersonalInfo = data.slice(personalHeaderIndex + 1, conditionHeaderIndex)
    res.ConditionInfo = medRecordGroupBy(data.slice(conditionHeaderIndex + 1))
    return res
  }
  if (personalHeaderIndex === -1 || visitorHeaderIndex === -1 || conditionHeaderIndex === -1) return {}
  res.PersonalInfo = data.slice(personalHeaderIndex + 1, visitorHeaderIndex)
  res.VisitorInfo = data.slice(visitorHeaderIndex + 1, conditionHeaderIndex)
  res.ConditionInfo = medRecordGroupBy(data.slice(conditionHeaderIndex + 1))
  return res
}

export const handleFieldValue = (value: string[], options: { [key in string]: { DisplayText: CustomI18NITF } }) => {
  const newValue: string[] = []
  if (!value || !Array.isArray(value)) return newValue
  value.forEach(item => {
    options?.[item] && newValue.push(item)
  })
  return newValue
}

export const getMedRecordValue = (item:any, language = 'zh') => {
  const { Children, FieldValue, OtherText, FieldStyle, Options, Default, Unit = '' } = item
  let value = ''
  let imgList = []
  let showValue = true

  switch (FieldStyle) {
    case 'TextMultiLang': {
      value = FieldValue?.[language]
      break
    }
    case 'Number':
    case 'PersonalId':
    case 'Text':
    case 'Age': {
      value = FieldValue
      break
    }
    case 'PhoneNumber': {
      if (FieldValue) {
        value = `${FieldValue.slice(0, 3)}****${FieldValue.slice(-4)}`
      }
      break
    }
    case 'DateOnly': {
      value = date.dateFormat(FieldValue, 'yyyy.MM.dd')
      break
    }
    case 'IncrementalNumber': {
      value = `${FieldValue}${Unit}`
      if (FieldValue === undefined) {
        value = ''
      }
      break
    }
    case 'VASRating': {
      value = `${FieldValue}级`
      if (FieldValue === undefined) {
        value = ''
      }
      break
    }
    case 'HourMinute': {
      if (FieldValue) {
        value = `${(FieldValue / 60).toFixed(1)} 小时`
      }
      break
    }
    case 'Boolean': {
      value = FieldValue ? '是' : '否'
      if (FieldValue === undefined) {
        value = ''
      }
      break
    }
    case 'UploadedFilePreviewUpload': {
      showValue = false
      imgList = FieldValue?.Records
      break
    }
    case 'SingleChoiceGender':
    case 'SingleChoice': {
      if (OtherText) {
        value = OtherText
      } else {
        value = Options?.[FieldValue]?.DisplayText?.[language]
      }
      break
    }
    case 'MultipleChoice':
    case 'SpecialChoice': {
      const arr:string[] = []
      FieldValue?.forEach((v:any) => {
        let text = Options?.[v]?.DisplayText?.[language]
        if (OtherText && v === 'Other') {
          text = OtherText
        }
        arr.push(text)
      })
      value = arr.join('、')
      break
    }
    case 'ShrinkTwo':
    case 'ShrinkThree': {
      value = Options?.[FieldValue]?.DisplayText?.[language]
      if (['Yes'].includes(FieldValue)) {
        Children.forEach((v:any, i:number) => {
          const { FieldValue } = v
          if (i === 0 && FieldValue) {
            value = `${value}：${getMedRecordValue(v, language).value}`
          }
          if (i === 1) {
            imgList = getMedRecordValue(v, language).imgList
          }
        })
      }
      break
    }
    case 'ShrinkBoolean': {
      value = FieldValue ? '是' : '否'
      if (Options) {
        value = Options?.[FieldValue ? 'Yes' : 'No']?.DisplayText?.[language]
      }
      if (FieldValue === undefined) {
        value = ''
      }
      if (FieldValue) {
        Children.forEach((v:any, i:number) => {
          if (i === 0) {
            const item = getMedRecordValue(v, language)
            if (item.value) {
              value = `${value}：${item.value}`
            }
            imgList = item.imgList
          }
          if (i === 1) {
            imgList = getMedRecordValue(v, language).imgList
          }
        })
      }
      break
    }
    default: {
      value = ''
    }
  }
  return { value, showValue, imgList }
}

const DIZZY = ['DizzyStartAge', 'MonthlyDizzyTimes', 'DizzyAverageMinutes']

export const isHiddenItem = (
  {
    Dependency,
    FieldName,
    fields
  }: { Dependency: Record<string, any>, FieldName: string, fields: Record<string, any>
  }
) => {
  let isHidden = false
  if (Dependency) {
    isHidden = Object.keys(Dependency).findIndex(dependency => {
      const isArray = Array.isArray(fields?.[dependency])
      return isArray ? fields?.[dependency].indexOf(Dependency[dependency]) <= 0 : fields?.[dependency] !== Dependency[dependency]
    }) > -1
  }
  if (['MedSufficient', 'MedIntakeStartTime', 'MedEffecacy'].includes(FieldName)) {
    if (!fields.MedsBeforeVisit || fields.MedsBeforeVisit.length === 0 || fields.MedsBeforeVisit.includes('None')) {
      isHidden = true
    }
  } else if (['MonthlyPainKillerIntakeTimes', 'PainKillerIntakeIntakeStartTime'].includes(FieldName)) {
    if (!fields.MonthlyPainKillers || fields.MonthlyPainKillers.length === 0 || fields.MonthlyPainKillers.includes('None')) {
      isHidden = true
    }
  } else if (DIZZY.includes(FieldName) && fields.MainStatement) {
    const MainStatement = fields.MainStatement || []
    isHidden = new Set([...MainStatement, 'ContinuousDizzy', 'RepeatedDizzy']).size >= MainStatement.length + 2
  }
  return isHidden
}
